from googlemaps import GoogleMaps
import twitter
#import tweepy
import os
import time
import urllib2
import sys
#Google Maps API Key: AIzaSyADP4in53jxtD-6eJRtIZdj7AW6ofvOo9o
#4463428 
conKey = "m8gDPJLNhJevZusJQ7pxA"
conSec = "3CNxg3fi7GLFqAnKG9kMXBtwi8o4L7m4gEdcvA5Iw"
accKey = "28868957-BB6Cn48MwWlqkIMBIWPe97XQZ7SzBjPuCUWxmK24" #bck 578324585-PXghXyuApG1PnyohaHV5h3VPa1hNyuF7Cbq2fI9H
accSec = "96KjPEdIXiCtwS2SOr7U7UOQt3Slk2d5ZIdYxxdvRE"#bck rKTBW85tLkKg8rh3daPec8fCJ4kUBhIbIZREq2qA

#auth = tweepy.OAuthHandler('m8gDPJLNhJevZusJQ7pxA', '3CNxg3fi7GLFqAnKG9kMXBtwi8o4L7m4gEdcvA5Iw')
#auth.set_access_token(accKey, accSec)
#twitterApi = tweepy.API(auth)
twitterApi = twitter.Api(consumer_key=conKey, consumer_secret=conSec,
                          access_token_key=accKey, access_token_secret=accSec)

 # access_token_key= accKey, access_token_secret=accSec)

gmapsApi = GoogleMaps("AIzaSyADP4in53jxtD-6eJRtIZdj7AW6ofvOo9o")
LASTIDSFILEPATH = "Assets/last_ids.txt"
RESULTSFILEPATH = "Assets/results.txt"
lastid = 0
lstOfProcessedIds = []
results = []
floatLastSearchTime = 0
floatCurrentTime = 0
blOverSpll = False
lstSearchTerms = ["Fuck", "Shit", "Cunt", "Bastard"]
term1 = lstSearchTerms[0]
term2 = lstSearchTerms[1]
term3 = lstSearchTerms[2]
term4 = lstSearchTerms[3]

countiesSwearingDict = {
"Antrim": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Armagh": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Carlow": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Cavan": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Clare": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Cork": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Derry": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Donegal": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Down": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Dublin": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Fermanagh": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Galway": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Kerry": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Kildare": [(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Kilkenny":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Laois":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Leitrim":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Limerick":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Longford":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Louth":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Mayo":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Meath":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Monaghan":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Offaly":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Roscommon":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Sligo":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Tipperary":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Tyrone":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Waterford":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Westmeath":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Wexford":[(term1, 0), (term2, 0), (term3, 0), (term4, 0)],
"Wicklow" :[(term1, 0), (term2, 0), (term3, 0), (term4, 0)]
                }

countiesPopDict = {
"Antrim":616384,
"Armagh":126803,
"Carlow":54612,
"Cavan":73183,
"Clare":117196,
"Cork":519032,
"Derry":211669,
"Donegal":161137,
"Down":489588,
"Dublin":1273069,
"Fermanagh":57527,
"Galway":250653,
"Kerry":145502,
"Kildare":210312,
"Kilkenny":95419,
"Laois":80559,
"Leitrim":31796,
"Limerick":191809,
"Longford":39000 ,
"Louth":122897,
"Mayo":130638,
"Meath":184135,
"Monaghan":60483,
"Offaly":76687,
"Roscommon":64065,
"Sligo":65393,
"Tipperary":158754,
"Tyrone":158460,
"Waterford":113795,
"Westmeath":86164,
"Wexford":145320,
"Wicklow":136640
                   }

# grab the last ID that the bot replied to, so it doesn't reply to earlier posts. (spam prevention measure)
def CheckLastIDPath():
  if os.path.exists(LASTIDSFILEPATH):
    fp = open(LASTIDSFILEPATH)
    global lastid
    lastid = fp.read().strip()
    fp.close()

    if lastid == '':
        lastid = 0
  else:
    lastid = 0

def WriteID(fields):
  if os.path.exists(LASTIDSFILEPATH):
    fileHandle = open(LASTIDSFILEPATH, "w")
    fileHandle.write(str(max(fields)))
    fileHandle.close()
    can1 = max(fields)
    tempHigh = fields[0]
    for x in fields:
      if x > tempHigh:
        tempHigh = x

    if can1 != tempHigh:
      print "Fuck Everything!"
      x = 5

def WriteResults(fields):
 if os.path.exists(RESULTSFILEPATH):
    fileHandle = open(RESULTSFILEPATH, "a+")
    for item in fields:
      fileHandle.write("\n%s" % (item))
    fileHandle.write("\n")
    fileHandle.flush()
    fileHandle.close()

def CheckResultsPath():

    if os.path.exists(RESULTSFILEPATH):
      fileHandle = open(RESULTSFILEPATH)
      stringEmptyTest = fileHandle.read().strip()
      fileHandle.close()
      if stringEmptyTest == "":
          return True
      else:
          return False

def GatherAndWrite():

  global floatCurrentTime
  global floatLastSearchTime
  global lstTweetUserNamesFP
  global lastid
  global blOverSpll
  global lstOfProcessedIds
  floatCurrentTime = time.time()
  resultsGathered = 0
  searchIndex = 0
  oldLastId = -1
  while resultsGathered < 200:

    CheckLastIDPath()

    if twitterApi.GetRateLimitStatus()["remaining_hits"] > 10:

      results = twitterApi.GetSearch(term=lstSearchTerms[searchIndex], per_page=50, since_id=int(lastid), geocode=(53.333333, -8, "300km"))
      floatLastSearchTime = time.time()
      resultsGathered += len(results)

    else:
      print "Twitter Hits < 10. Quitting"
      print twitterApi.GetRateLimitStatus()["reset_time"]
      sys.exit()

    counter = 0
    if(len(results) > 0):
      for result in results:
        if(result.location != None):

          if result.id not in lstOfProcessedIds:

            for key in  countiesSwearingDict.iterkeys():

              if result.location.encode("utf-8").find(key) != -1:
                print "Result Accepted"
                newValue = countiesSwearingDict[key][searchIndex][1]
                newValue += 1
                countiesSwearingDict[key][searchIndex] = (countiesSwearingDict[key][searchIndex][0], newValue)
                newValue = 0
                lstOfProcessedIds.append(result.id)
                print "Result Processed"

          else:
            print "Result Rejected. Already Processed"
            #results.pop(counter)

        else:
          print "Result Rejected. No Location Data"
        #counter += 1



      #results.pop(counter)


    if(searchIndex < 3):
      searchIndex += 1
    else:
      searchIndex = 0

    if len(results) > 0:
      idList = []
      for x in results:
       idList.append(x.id)

      WriteID(idList)
    index = 0
    for item in results:
      results.pop(index)
      if index < len(results):
        index += 1

  print "Finished!"
#      for test in results:
#        print test.id
#      x = 5

  #fields = ["Has Geo: True" + "","ID: %d"%(result.id) + "","Message: %s" % ((result.text).encode("utf-8"))+ "",
        #"Coordinates: " + str(result.geo["coordinates"]).encode("utf-8")]

 # WriteResults(fields) 
  #print result.geo["coordinates"]
  #print gmapsApi.latlng_to_address(result.geo["coordinates"][0],result.geo["coordinates"][1])




#  if blOverSpll == True:
#    WriteID(lastid)
#  else:


#         else:
#          lstTweetUserNamesFP.append( (result._user._screen_name,result.id,result.text))

  #####################################################################################################        
  #Processing the tweets with no location data.
  #1. Loop through the list
  #2 incCounter counts the number of items processed. 
  # If its less than our Twitter Hit Budget, we can process another.
  #3. Use the user's name(first field in the tuple) to retrieve the whole user object.
  #4. Check the user's location field, if it's not None or empty:
  #5. Create a list of things about the tweet we want to write to file, and write them.
  #6. Else, record the id as the last id processed, and leave the loop.
  ######################################################################################################








#      for userNameTuple in lstTweetUserNamesFP:
#        
#        if(twitterApi.GetRateLimitStatus()["remaining_hits"] > 0):
#          try:
#            user = twitterApi.GetUser(userNameTuple[0])
#          except twitter.TwitterError:
#            print "Exception: Name not found: userNameTuple[0]"
#          
#          
#          if(user.location != None or "" ):
#            fields = ["Has Geo: False", "ID: %d"%(userNameTuple[1])+ "","Message: %s"%(userNameTuple[2]).encode("utf-8") + "","Location: " + user.location.encode("utf-8")]
#            WriteResults(fields)
#            intCounter+= 1
#        else:
#          
#          lastid = userNameTuple[1]
#          blOverSpll = True
#          print "Out of Twitter hits. Writing last id to file"
#          
#          break

  #############################################################################################################
  #1. Open the lastids file.
  #2. If we ran out of Twitter hits
  #3. Then write in the id of the last tweet we processed.
  #4. Else, write in the highest id in the list of results
  #5. Close both filehandles, and print out the completed results file.
  ###############################################################################################################           




        #print twitterApi.GetRateLimitStatus()["remaining_hits"]



        #Read()

  #Read()
#        twitterApi.GetRateLimitStatus





def Read():
  #search terms
  stHasGeo = "Has Geo: "
  stID = "ID: "
  stMessage = "Message: "
  stLocation = "Location: "

  if os.path.exists(RESULTSFILEPATH):
    fileHandle = open(RESULTSFILEPATH, "r")
    for line in fileHandle.readlines():
      line.strip()
      x = 5
      if line.find(stHasGeo) != -1:
          beginIndex = (line.find(stHasGeo) + len(stHasGeo))
          print " Pulled Has Geo: " + line[beginIndex:-1]

      elif line.find(stID) != -1:
          beginIndex = (line.find(stID) + len(stID))
          print " Pulled ID: " + line[beginIndex:-1]
      elif line.find(stMessage) != -1:
          beginIndex = (line.find(stMessage) + len(stMessage))
          print " Pulled Message: " + line[beginIndex:-1]

      elif line.find(stLocation) != -1:
          beginIndex = (line.find(stLocation) + len(stLocation))
          print " Pulled Location: " + line[beginIndex:-1]


      print line,
    fileHandle.close()


def main():

  blWriting = CheckResultsPath()

  #if(blWriting == True):
  print "Remaining Hits: %d" % (twitterApi.GetRateLimitStatus()["remaining_hits"])
  GatherAndWrite()

  #else:
  # Read()






     # WriteID(result.id)





if __name__ == '__main__':
  main()
